<!--xgplayer  -->
<template>
  <div class="cam" v-if="rtsp != ''">
    <div class="video" v-show="isPlay" :id="camDOMid" ref="video"></div>
  </div>
</template>

<script>
  import Player from 'xgplayer';
  import FlvJsPlayer from 'xgplayer-flv.js';
  export default {
    name: "CameraItem5",
    components: {},
    props: ['camDOMid', 'rtsp'],
    data() {
      return {
        isPlay: false, //是否显示播放画面
        player: null, //播放实例
        lastDecodedFrame: 0, //最后一个decodedFrame
        sameCount: 0, //decodedFrame不变次数
        currentTime: 0, //当前时间
        lastCurrentTime: 0, //最后的时间
        timer: "", //定时器
      }
    },
    computed: {

    },
    watch: {
      //监听rtsp变化，改变播放地址
      rtsp: {
        handler(newval) {
          this.player.src = this.playUrl(newval)
        }
      }
    },
    created() {
      //10秒定时任务判断画面时间是否没变化，没变化就重连
      let _this = this;
      _this.timer = setInterval(() => {
      if (_this.lastCurrentTime == _this.currentTime) {
        console.log("10秒定时任务判断画面时间没变化，销毁重连",new Date());
        _this.currentTime = 0;
        _this.lastCurrentTime = 0;
        if (_this.player) { //如果有实例，就销毁
          _this.player.destroy(); //销毁
        }
        _this.getData() //重连
      } else {
        _this.currentTime = _this.player.currentTime
      }
    }, 50 * 1000);
    },

    mounted() {
      window.onfocus = () => {
        console.log("-----------")
        // let end = player.buffered.end(0) - 1;
        // this.player.currentTime = end;
      };
      //获取数据，连接
      this.getData(this.rtsp);
      //检测网络连接，销毁重连
      let _this = this;
      window.addEventListener("online", () => {
        if (_this.player) {
          _this.currentTime = 0;
          _this.lastCurrentTime = 0;
          _this.player.destroy(); //销毁
          _this.getData() //重连
        }
      });
      //12小时后，销毁重连
      setTimeout(() => {
        console.log("12小时后，销毁重连");
        if (_this.player) {
          _this.currentTime = 0;
          _this.lastCurrentTime = 0;
          _this.player.destroy(); //销毁
          _this.getData() //重连
        }
      }, 12 * 60 * 60 * 1000);
    },
    methods: {
      // 设置视频配置(注意：initPlayer应放在异步函数里或mounted之后，不可在created里直接加载，否则不生效)
      initPlayer(url) {
        this.isPlay = true;
        this.$nextTick(function () {
          let _this = this;
          this.player = new FlvJsPlayer({
            id: this.camDOMid,
            url: url,
            fitVideoSize: 'auto',
            hasStart: true,
            autoplay: true, //自动播放，设置自动播放必要参数
            autoplayMuted: true, //自动播放静音，设置自动播放参数必要参数
            volume: 0,
            defaultMuted: true,
            isLive: true,
            playsinline: false,
            screenShot: false,
            fluid: true,
            aspectRatio: '16:9',
            whitelist: [''],
            // ignores: ['time'],
            closeVideoClick: false,
            // errorTips: '<span class="app-error">无视频源</span>',
            customConfig: {
              isClickPlayBack: false
            },
            flvOptionalConfig: {
              enableWorker: true,
              enableStashBuffer: false, //启用缓存
              stashInitialSize: 4096, //缓存大小4m
              lazyLoad: false,
              lazyLoadMaxDuration: 40 * 60,
              autoCleanupSourceBuffer: true, //自动清除缓存
              autoCleanupMaxBackwardDuration: 35 * 60,
              autoCleanupMinBackwardDuration: 30 * 60,
              reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
            } //flv.js可选配置项 [flv.js配置](https://github.com/bilibili/flv.js/blob/master/docs/api.md#config)
          });
          this.player.once('canplay', () => {})
          this.player.once('error', () => {
            if (this.player) {
              this.player.replay();
            }
            return;
          })
          this.player.once('pause', () => {
            // console.log('pause')
          })
          this.player.once('canplaythrough', () => {
            console.log('可流畅播放')
          })
          //检测画面是否卡死。如果decodedFrames不再发生变化,就销毁掉该实例并进行重新连接。这个函数基本是1秒执行一次的。
          this.player.on("statistics_info", function (res) {
            console.log(_this.player.currentTime,'==================')
            if (_this.lastDecodedFrame == 0) {
              console.log("=结束")
              _this.lastDecodedFrame = res.decodedFrames;
              return;
            }
            if (_this.lastDecodedFrame != res.decodedFrames) {
              console.log("播放中：lastDecodedFrame="+_this.lastDecodedFrame+";res.decodedFrames="+res.decodedFrames)
              _this.lastDecodedFrame = res.decodedFrames;
              _this.lastCurrentTime = _this.player.currentTime; //最后的时间
              _this.sameCount = 0;
            } else {
              _this.sameCount++;
              console.log("decodedFrames没有发生变化第", _this.sameCount, "次。时间：", new Date());

              if (_this.sameCount > 50) {
                //decodedFrames10次不变，则判断为画面卡死，销毁实例进行重连
                console.log("画面卡死，进行重连————————", "时间", new Date());
                _this.lastDecodedFrame = 0;
                _this.sameCount = 0;

                if (_this.player) {
                  _this.currentTime = 0;
                  _this.lastCurrentTime = 0;
                  _this.player.destroy(); //销毁
                  _this.getData() //重连
                }
              }
            }
            console.log("最后的时间：", _this.lastCurrentTime, "   10秒前的时间：",_this.currentTime);
          });
          // //优化延迟
          // setTimeout(() => {
          //   setInterval(() => {
          //     console.log("缓冲区末尾",this.player.getBufferedRange()[1],"当前位置：",this.player.currentTime);
          //     if(this.player.getBufferedRange()[1]){
          //       let end = this.player.getBufferedRange()[1];
          //       let diff = end - this.player.currentTime;//获取buffered与currentTime的差值
          //       if (diff >= 1) {//如果差值大于等于3 手动跳帧 这里可根据自身需求来定
          //         this.player.currentTime = this.player.getBufferedRange()[1];//手动跳帧
          //         console.log("优化延迟，手动跳帧，时间：",new Date());
          //       }
          //     }
          //   }, 2000); //2000毫秒执行一次
          // }, 3000);

        })
      },
      //获取数据，连接
      getData() {
        let playUrl = this.playUrl(this.rtsp)
        this.initPlayer(playUrl)
        console.log("playUrl", playUrl);
      },
      //拼接地址
      playUrl(val) {
        // http://192.168.56.1:null/hls?url=
        // var webSocketUrl = "92.168.101.61:8099"; //webSocket的ip
        // let playUrl = "ws://" + webSocketUrl + "/live?url=" + val; //播放地址
        let playUrl = val;
        // let playUrl = "ws://192.168.56.1:8099/live?url=" + val; //播放地址
        return playUrl;
      },

    },
    beforeDestroy() {
      clearInterval(this.timer)
      if (this.player) {
        this.player.destroy();
      }
      //销毁监听
      let _this = this;
      console.log("销毁")
      window.removeEventListener('online', () => {
        console.log("监听销毁")
        if (_this.player) {
          _this.currentTime = 0;
          _this.lastCurrentTime = 0;
          _this.player.destroy(); //销毁
          _this.getData() //重连
        }
      }, true);
    },

  }

</script>
<style lang='scss'>
  .video {
    width: 50%;
    height: 50%;
  }
</style>
